import json

from django.http import JsonResponse
from django.views import View

from api import GENGGAI2FENJING, GENGGAI2KUOCHONG
from Movie.models import *


# 创建一条场景
from api.GENGGAI2FENJING import fenjing2localurl


class CreateMovie(View):
    def post(self, request):
        if not request.session.get('is_login', None) or not request.session['is_login']:
            return JsonResponse({'code': 0, 'message': '用户未登录'})
        kwargs: dict = json.loads(request.body)
        if kwargs.keys() != {'description', 'title'}:
            return JsonResponse({'code': 400, 'message': '参数错误'})
        user_id = request.session.get('user_id', None)
        user = User.objects.filter(id=user_id)
        if not user.exists():
            return JsonResponse({'code': 0, 'message': '用户不存在'})
        user = user.get()
        title = kwargs['title']
        description = kwargs['description']
        movie = Movie.objects.create(title=title, description=description, user=user)
        return JsonResponse({'code': 1, 'message': '创建成功', 'mid': movie.id})


# 查询该用户创建的场景列表
class QueryMovie(View):
    def post(self, request):
        if not request.session.get('is_login', None) or not request.session['is_login']:
            return JsonResponse({'code': 0, 'message': '用户未登录'})
        kwargs: dict = json.loads(request.body)
        if kwargs.keys() != {'description', 'title'}:
            return JsonResponse({'code': 400, 'message': '参数错误'})
        user_id = request.session.get('user_id', None)
        user = User.objects.filter(id=user_id)
        if not user.exists():
            return JsonResponse({'code': 0, 'message': '用户不存在'})
        user = user.get()
        movie_list = Movie.objects.filter(user=user)
        res_list = [{'mid': a.id, 'title': a.title, 'description': a.description} for a in movie_list]
        return JsonResponse({'code': 1, 'message': '查询成功', 'result': res_list})


# TODO:根据一条场景描述创建分镜
def CreateStoryFromMovie(description) -> list:
    return []


# 查询某description的所有分镜
class QueryStory(View):
    def post(self, request):
        # if not request.session.get('is_login', None) or not request.session['is_login']:
        #     return JsonResponse({'code': 0, 'message': '用户未登录'})
        kwargs: dict = json.loads(request.body)
        if kwargs.keys() != {'description'}:
            return JsonResponse({'code': 400, 'message': '参数错误'})
        # user_id = request.session.get('user_id', None)
        # user = User.objects.filter(id=user_id)
        # if not user.exists():
        #     return JsonResponse({'code': 0, 'message': '用户不存在'})
        # user = user.get()
        description = kwargs['description']
        # movie = Movie.objects.get(id=mid)
        res_list = []
        # if movie.flag == 0:
        story_list = GENGGAI2FENJING.genggai2fenjing(description)
        # for a in range(len(story_list)):
            # story = StoryBoard.objects.create(index=a+1, description=story_list[a], movie = movie)
            # res_list.append({'sid': story.id, 'index': story.index, 'description': story.description})
        # else:
        #     story_list = StoryBoard.objects.filter(movie=movie).order_by('index')
        #     res_list = [{'sid': story.id, 'index': story.index, 'description': story.description} for story in story_list]
        return JsonResponse({'code': 1, 'message': '查询成功', 'result': [a[0] for a in story_list]})


# 为场景新增一条分镜
class AddStory(View):
    def post(self, request):
        if not request.session.get('is_login', None) or not request.session['is_login']:
            return JsonResponse({'code': 0, 'message': '用户未登录'})
        kwargs: dict = json.loads(request.body)
        if kwargs.keys() != {'mid', 'index', 'description'}:
            return JsonResponse({'code': 400, 'message': '参数错误'})
        # user_id = request.session.get('user_id', None)
        # user = User.objects.filter(id=user_id)
        # if not user.exists():
        #     return JsonResponse({'code': 0, 'message': '用户不存在'})
        # user = user.get()
        mid = int(kwargs['mid'])
        index = int(kwargs['index'])
        description = kwargs['description']
        movie = Movie.objects.get(id=mid)
        story_list = StoryBoard.objects.filter(movie=movie).order_by('index')
        for a in story_list:
            if a.index >= index:
                a.index += 1
                a.save()
        StoryBoard.objects.create(index=index, description=description, movie=movie)
        res_list = [{'sid': story.id, 'index': story.index, 'description': story.description}
                    for story in StoryBoard.objects.filter(movie=movie).order_by('index')]
        return JsonResponse({'code': 1, 'message': '创建成功', 'result': res_list})


# 修改某条分镜
class EditStory(View):
    def post(self, request):
        if not request.session.get('is_login', None) or not request.session['is_login']:
            return JsonResponse({'code': 0, 'message': '用户未登录'})
        kwargs: dict = json.loads(request.body)
        if kwargs.keys() != {'sid', 'index', 'description'}:
            return JsonResponse({'code': 400, 'message': '参数错误'})
        # user_id = request.session.get('user_id', None)
        # user = User.objects.filter(id=user_id)
        # if not user.exists():
        #     return JsonResponse({'code': 0, 'message': '用户不存在'})
        # user = user.get()
        sid = int(kwargs['sid'])
        index = int(kwargs['index'])
        description = kwargs['description']
        story = StoryBoard.objects.get(id=sid)
        story_list = StoryBoard.objects.filter(movie=story.movie).order_by('index')
        for a in story_list:
            if a.index >= index:
                a.index += 1
                a.save()
        story.index = index
        story.description = description
        story.save()
        return JsonResponse({'code': 1, 'message': '创建成功',
                             'result': {'sid': story.id, 'index': story.index, 'description': story.description}})


# # TODO:根据某条分镜创建图片，返回的图片在本地储存的url
# def CreatePictureFromStory(description) -> str:
#
#     pass


# 查询某分镜的图片
class GenPicture(View):
    def post(self, request):
        # if not request.session.get('is_login', None) or not request.session['is_login']:
        #     return JsonResponse({'code': 0, 'message': '用户未登录'})
        kwargs: dict = json.loads(request.body)
        if kwargs.keys() != {'story'}:
            return JsonResponse({'code': 400, 'message': '参数错误'})
        story = kwargs['story']
        # if picture_list.count() == 0:
        url1, url2 = fenjing2localurl(story)

        return JsonResponse({'code': 1, 'message': '创建成功', 'result': url1})


class GenDes(View):
    def post(self, request):
        # if not request.session.get('is_login', None) or not request.session['is_login']:
        #     return JsonResponse({'code': 0, 'message': '用户未登录'})
        kwargs: dict = json.loads(request.body)
        if kwargs.keys() != {'short_description'}:
            return JsonResponse({'code': 400, 'message': '参数错误'})
        short_description = kwargs['short_description']
        res = GENGGAI2KUOCHONG.genggai2kuozhong(short_description)
        return JsonResponse({'code': 1, 'message': '创建成功', 'result': res})
